package com.acme.bankapp.mail;

public class EMailService {
	private Queue queue = new Queue();
	private volatile boolean stopped = false;

	public EMailService() {
		Thread thread = new Thread() {
			public void run() {
				while (!EMailService.this.stopped) {
					EMail email = EMailService.this.queue.get();
					if (email.isStop()) {
						continue;
					}
					EMailService.this.send();
					System.out.println("New EMail for " + email.toString());
				}
			}
		};
		thread.start();
	}

	public void sendNotificationEmail(EMail email) {
		if (!this.stopped) {
			this.queue.add(email);
		}
	}

	private void send() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void close() {
		this.stopped = true;
		EMail stopEMail = new EMail();
		stopEMail.setStop(true);
		this.queue.add(stopEMail);
	}

}
